package com.duan.controller;

import com.duan.base.JSONResponse;
import com.duan.mapper.UserMapper;
import com.duan.pojo.User;
import com.duan.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService){
        this.userService = userService;
    }

    /***
     * 登录功能
     * @param user 前端上传信息封装好的User
     * @param session 上下文
     * @return 返回自定义的返回值对象，会自动转换为JSON给前端
     */
    @PostMapping("/api/user/login")
    public JSONResponse  login(@RequestBody User user, HttpSession session){
        log.debug(user.toString());
        String username = user.getUsername();
        String password = user.getPassword();

        User user_res = userService.login(username, password);

        JSONResponse jsonResponse = new JSONResponse(); // 返回类型对象
        if(user_res != null){ //登录成功
            log.debug("{} + {} 登录成功", username, password);
            jsonResponse.setSuccess(true);
            session.setAttribute("currentUser", user_res);
        }else{ // 登录失败
            log.debug("{} + {} 登录失败", username, password);
            jsonResponse.setSuccess(false);
            jsonResponse.setCode("LOG001");
            jsonResponse.setMessage("用户不存在");
        }

        return jsonResponse;
    }



}
